package com.gwt.tirso.gymkhana.server;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwt.tirso.gymkhana.client.ILoginService;
import com.gwt.tirso.gymkhana.client.Person;

@SuppressWarnings("serial")
public class LoginServiceImpl extends RemoteServiceServlet implements
		ILoginService {

	//private IPersonDAO pdao;
	
	@SuppressWarnings("finally")
	@Override
	public Person login(String email, String pass) {
		//pdao = new JDBCPersonDAO();
		//Person p = pdao.selectPersonByEmailAndPass(email, pass);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Person p = null;
		try{
			String query = "select from " + Person.class.getName() + " where email == '" + email + "' && password == '" + pass + "'";
			List<Person> lp = (List<Person>) pm.newQuery(query).execute();
			p = lp.get(0);
		}finally{
			if(p != null){
				storeUserInSession(p);
			}
			pm.close();
			return p;	
		}
	}


	private void storeUserInSession(Person p) {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		session.setAttribute("user", p);

	}

	@Override
	public Person loginFromSessionServer() {
		Person p = getUserFromSession();
		return p;
	}

	private Person getUserFromSession() {
		Person user = null;
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession session = httpServletRequest.getSession();
		Object userObj = session.getAttribute("user");
		if (userObj != null && userObj instanceof Person) {
			user = (Person) userObj;
		}
		return user;
	}

	@Override
	public void logout() {
		deleteUserFromSession();
	}

	private void deleteUserFromSession() {
		HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
		HttpSession httpSession = httpServletRequest.getSession();
		httpSession.removeAttribute("user");
	}

}
